import React, { Component, Fragment } from 'react'
import { inject, observer } from 'mobx-react/index'
import { Form, Input, Button, Card, Checkbox, message, Spin, Divider } from 'antd'
import { address } from '@/Utils/apiConfig'
import getData from '@/Utils/fecth'

const { leagueManagement: { getPeerOfCreateChannel, createChannel }} = address

const FormItem = Form.Item
const CheckboxGroup = Checkbox.Group
const { TextArea } = Input

@inject('SocketModel')
@observer
class CreateChannel extends Component {
  constructor(props) {
    super(props)
    this.state = {
      checkedList: [],
      indeterminate: false,
      checkAll: false,
      initialValues: {
        options: [],
      },
      loading: false,
      orgList: [],
      orgIds: [],
      consortiumId: props.match.params.id,
      name: props.match.params.name,
    }
    this.orgList = []
  }

  formRef = React.createRef();

  componentDidMount() {
    const id = this.state.consortiumId || ''
    this.getPeerOfChannel(id)
  }

  getPeerOfChannel = async(id) => {
    let orgList = null
    let orgIds = null
    await getData().get(getPeerOfCreateChannel.format({ consortiumId: id })).then(res => {
      switch (res.status) {
      case 200:
        orgList = res.data
        orgIds = orgList.map(item => { return item.id })
        this.setState({
          orgList,
          orgIds,
          loading: false,
        })
        break
      default:
        message.error('请求失败')
        break
      }
    })
    return orgList
  }

  onChange = checkedList => {
    this.setState({
      checkedList,
      indeterminate: !!checkedList.length && checkedList.length < this.state.orgIds.length,
      checkAll: checkedList.length === this.state.orgIds.length,
    })
  };

  onCheckAllChange = e => {
    this.formRef.current.setFieldsValue({
      options: e.target.checked ? this.state.orgIds : [],
    })
    this.setState({
      checkedList: e.target.checked ? this.state.orgIds : [],
      indeterminate: false,
      checkAll: e.target.checked,
    })
  };

  onFinish = async(values) => {
    const { checkedList } = this.state
    let params = {
      consortiumId: this.state.consortiumId,
      c_name: values.c_name,
      c_description: values.c_description,
      c_policy: `${values.c_policy}`,
      orgIds: checkedList,
    }
    this.setState({
      loading: true,
    })
    let res = await getData().post(createChannel, params)
    this.setState({
      loading: false,
    })
    if (res && res.status === 200) {
      message.success('通道创建中')
      this.props.history.goBack()
    }
  }

  render() {
    const { initialValues, orgList, loading } = this.state
    return (
      <Spin spinning={loading}>
        <Card className="common" bodyStyle={{ padding: '30px' }}>
          <Form
            ref={this.formRef}
            initialValues={initialValues}
            style={{ width: '550px' }}
            labelCol={{ span: 5 }}
            onFinish={this.onFinish}>
            <FormItem
              name="c_name"
              label="通道名称"
              rules={[
                {
                  required: true,
                  message: '请输入通道名称',
                },
                () => ({
                  validator(rule, value) {
                    if (value && !(/^([a-z1-9]+)$/.test(value))) {
                      return Promise.reject('通道名称只能由小写字母及数字1-9组成')
                    }
                    return Promise.resolve()
                  },
                }),
              ]}
            >
              <Input placeholder="请输入" maxLength={15} />
            </FormItem>
            <FormItem className="form-item-required" label={<div className="common-select">选择组织</div>} rules={[{ required: true }]}>
              <Card bordered={false} bodyStyle={{ padding: '0' }} >
                <FormItem noStyle>
                  <Checkbox
                    style={{ lineHeight: '35px', paddingLeft: '20px' }}
                    indeterminate={this.state.indeterminate}
                    onChange={this.onCheckAllChange}
                    checked={this.state.checkAll}
                  >
                    全选
                  </Checkbox>
                </FormItem>
                <FormItem name="options" rules={[{ required: true, message: '请选择组织' }]} noStyle>
                  <CheckboxGroup style={{ width: '100%', background: '#ffffff' }} onChange={this.onChange} >
                    {orgList.map((item) => {
                      return (
                        <Fragment key={item.id}>
                          <Checkbox
                            key={item.id}
                            style={{ lineHeight: '35px', margin: '0 8px 0 0' }}
                            value={item.id}
                          >
                            {item.display_name || '无'}
                          </Checkbox>
                        </Fragment>
                      )
                    })}
                  </CheckboxGroup>
                </FormItem>
              </Card>
            </FormItem>
            <FormItem
              name="c_description"
              label="描述"
              rules={[{ type: 'string', min: 0, max: 500, message: '最多输入500字符' }]}
            >
              <TextArea rows={5} placeholder="请输入描述，最多输入500字符" />
            </FormItem>
            <Divider className="common-form-divider" />
            <FormItem label=" " style={{ marginBottom: 0 }}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={() => { this.props.history.goBack() }} disabled={this.state.cancelDisabled}>
                取消
              </Button>
            </FormItem>
          </Form>
        </Card>
      </Spin>
    )
  }
}

export default CreateChannel
